import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'package:dk_flutter_module_sale/common/config/page_base_common.dart';
import 'package:dk_flutter_module_sale/common/user_track/user_track.dart';
import 'package:dk_flutter_module_sale/config/route/common_widget_route.dart';
import 'package:dk_flutter_module_sale/sale/api/sale_in_api.dart';
import 'package:dk_flutter_module_sale/sale/sale_in/following_record/bean/history_record_bean.dart';
import 'package:dk_flutter_module_sale/sale/sale_in/following_record/bean/record_config_bean.dart';
import 'package:dk_flutter_module_sale/sale/sale_in/following_record/widget/mutiple_remark_widget.dart';
import 'package:dk_flutter_module_sale/sale/sale_in/following_record/widget/record_price_widget.dart';
import 'package:dk_flutter_module_sale/sale/sale_in/following_record/widget/record_select_time_widget.dart';
import 'package:dk_flutter_module_sale/sale/sale_in/following_record/widget/step_widget.dart';
import 'package:dk_flutter_module_sale/sale/sale_in/following_record/widget/widget_record_choice.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/painting.dart';

@ARoute(url: CommonWidgetRoute.COMMON_FOLLOWING_RECORD)
class PageFollowingRecord extends CommonPageWithTrack {
  final BoostRouteOption option;
  PageFollowingRecord(this.option) : super();

  @override
  void trackStatistics() {
    UserTrack.trackViewScreen("收房-房源跟进记录-列表", null);
  }
  @override
  void onInitState(CommonPageBloc pageBloc, {Map<String, Bloc> extraBlocMap}) {
    loadRecordConfigs(pageBloc);
  }

  void loadRecordConfigs(CommonPageBloc pageBloc) {
    Map<String, dynamic> paramsMap = {};
    paramsMap["model_name"] = "house_resources";
    paramsMap["model_key"] = "status";
    paramsMap["model_value"] = option.params["houseStatus"];
    pageBloc.dataHttpGet(
      path: SaleInApi.followRecordConfigUrl,
      queryMap: paramsMap,
      handleResult: (dynamic data) {
        RecordConfigBean configData = RecordConfigBean.fromJson(data);
        List<TextEditingController> remarkControllers =
            List<TextEditingController>();
        List<FocusNode> focusNodes = List<FocusNode>();
        List<String> remarkContents = List<String>();

        List<DkPicker> timePickers = List<DkPicker>();
        List<List<int>> selectIndexLists = List<List<int>>();

        List<TextEditingController> priceControllers =
            List<TextEditingController>();
        List<String> priceContents = List<String>();

        //单选多选
        List<int> singleIndexs =  List<int>();
        List<List<int> > multipleIndexLists =  List<List<int> >();

        for (ConfigBean configBean in configData.list) {
          if (configBean.type == "填写") {
            if (configBean.inputType == "单行数字") {
              priceControllers.add(TextEditingController(text: ""));
              priceContents.add("");
            } else {
              remarkControllers.add(TextEditingController(text: ""));
              focusNodes.add(FocusNode());
              remarkContents.add("");
            }
      } else if (configBean.type == "下拉") {
            DkPicker picker;
            timePickers.add(picker);
            List<int> selectIndexList = List<int>();
            selectIndexLists.add(selectIndexList);
            debugPrint("下拉----");
          } else if(configBean.type == "单选") {
            singleIndexs.add(-1);
          } else if(configBean.type == "多选") {
            List<int> multipleIndexList =  List<int>();
            multipleIndexLists.add(multipleIndexList);
          }

        }
        pageBloc.switchPage(FollowingRecordWidget(
            pageBloc,
            configData,
            remarkControllers,
            focusNodes,
            remarkContents,
            option,
            timePickers,
            selectIndexLists,
            priceContents,
            priceControllers,
            singleIndexs,
            multipleIndexLists
        ));
      },
      showLoading: false,
      showFailMsg: false,
      showSuccessMsg: false,
    );
  }
}

// ignore: must_be_immutable
class FollowingRecordWidget extends StatefulWidget {
  final CommonPageBloc pageBloc;
  final RecordConfigBean recordConfigBean;
  final List<TextEditingController> remarkControllers;
  final List<FocusNode> focusNodes;
  final List<String> remarkContents;

  final List<DkPicker> timePickers;
  final List<List<int>> selectIndexLists;

  final List<TextEditingController> priceControllers;
  final List<String> priceContents;

  final List<int> singleIndexs ;
  final List<List<int> > multipleIndexLists ;

  BoostRouteOption option;

  FollowingRecordWidget(
      this.pageBloc,
      this.recordConfigBean,
      this.remarkControllers,
      this.focusNodes,
      this.remarkContents,
      this.option,
      this.timePickers,
      this.selectIndexLists,
      this.priceContents,
      this.priceControllers,
      this.singleIndexs,
      this.multipleIndexLists
      );
  @override
  FollowingRecordState createState() {
    return FollowingRecordState(
        this.pageBloc,
        recordConfigBean,
        remarkControllers,
        focusNodes,
        remarkContents,
        this.timePickers,
        this.selectIndexLists,
        this.priceContents,
        this.priceControllers,
        this.singleIndexs,
        this.multipleIndexLists
    );
  }
}

class FollowingRecordState extends State<FollowingRecordWidget>
    with SingleTickerProviderStateMixin {
  CommonPageBloc pageBloc;
  //单选多选
  List<int> singleIndexs;
  List<List<int> > multipleIndexLists;

  //历史记录
  HistoryRecordBean historyRecordBean;
  //配置项
  RecordConfigBean recordConfigBean;
  //备注
  List<TextEditingController> remarkControllers;
  List<FocusNode> focusNodes;
  List<String> remarkContents;
  // 下拉弹框
  List<DkPicker> timePickers;
  List<List<int>> selectIndexLists;
  //价格输入框
  List<TextEditingController> priceControllers;
  List<String> priceContents;

  //上传参数
  List<Map<String, dynamic>> submitMapList = List<Map<String, dynamic>>();

  FollowingRecordState(
      this.pageBloc,
      this.recordConfigBean,
      this.remarkControllers,
      this.focusNodes,
      this.remarkContents,
      this.timePickers,
      this.selectIndexLists,
      this.priceContents,
      this.priceControllers,
      this.singleIndexs,
      this.multipleIndexLists
      );
  @override
  void initState() {
    super.initState();

    for (int i = 0; i < priceControllers.length; i++) {
      TextEditingController priceController = priceControllers[i];
      priceController.addListener(() {
        priceContents[i] = priceController.text;
        debugPrint("价格:${priceContents[i]}");
      });
    }

    for (int i = 0; i < remarkControllers.length; i++) {
      TextEditingController remarkController = remarkControllers[i];
      remarkController.addListener(() {
        remarkContents[i] = remarkController.text;
        debugPrint("备注:${remarkContents[i]}");
      });
    }
    loadHistoryRecords();

  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: SafeArea(
        bottom: true,
        child: Scaffold(
          appBar: DkAppBar(DKAppBarParams.withBackNoMenu(pageBloc.context,
              titleContent: "跟进记录")),
          backgroundColor: Colors.white,
          resizeToAvoidBottomPadding: true,
          body: Stack(
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(bottom: 64),
                child: CustomScrollView(
                  physics: ScrollPhysics(),
                  slivers: getSliverToBoxAdapters(),
                ),
              ),
              DkVisibilityCompose(VisibilityComposeOption.gone(
                (BuildContext context) {
                  return Positioned(
                    bottom: 5,
                    left: 0,
                    right: 0,
                    child: Container(
                      height: 59,
                      padding: EdgeInsets.only(left: 16, right: 16, top: 5),
                      decoration: new BoxDecoration(
                        color: Colors.white,
                        boxShadow: [
                          BoxShadow(
                              color: Color.fromRGBO(0, 0, 0, 0.5),
                              offset: Offset(0, 1.0),
                              blurRadius: 3.0,
                              spreadRadius: 0.0)
                        ],
                      ),
                      child: GestureDetector(
                        child: Card(
                          color: Color(0xff3DBCC6),
                          elevation: 0.0,
                          clipBehavior: Clip.antiAliasWithSaveLayer,
                          shape: const RoundedRectangleBorder(
                            side: BorderSide.none,
                            borderRadius: BorderRadius.all(
                              Radius.circular(3),
                            ),
                          ),
                          child: Center(
                            child: Text(
                              '提交',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 16,
                              ),
                            ),
                          ),
                        ),
                        onTap: () {
                          submitFollowingRecords(context);
                        },
                      ),
                    ),
                  );
                },
                visible: (objNotEmpty(recordConfigBean) &&
                    objNotEmpty(recordConfigBean.list) &&
                    recordConfigBean.list.length > 0),
              )),
              Positioned(
                bottom: 0,
                left: 0,
                right: 0,
                child: Container(
                  height: 6,
                  color: Colors.white,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget getToastTipWidget(String title) {
    return Container(
      height: 76,
      width: 175,
      padding: EdgeInsets.only(left: 15, right: 15, top: 15, bottom: 15),
      decoration: BoxDecoration(
        color: Color.fromRGBO(2, 2, 2, 0.7),
        borderRadius: BorderRadius.circular(3),
      ),
      child: Center(
        child: Text(
          title,
          textAlign: TextAlign.center,
          maxLines: 2,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
              color: Colors.white, fontSize: 16, fontWeight: FontWeight.normal),
        ),
      ),
    );
  }

  void addFollowingRecord(String title, String answer, String inputType) {
    Map<String, dynamic> paramsMap = {};
    paramsMap["title"] = title;
    paramsMap["answer"] = answer;
    paramsMap["inputType"] = inputType;
    submitMapList.add(paramsMap);
  }

  void submitFollowingRecords(BuildContext context) {
    submitMapList.clear();
    bool canContinue = true;
    if (recordConfigBean != null) {
      int index = 0;
      int downIndex = 0;
      int priceIndex = 0;
      int singleChoiceIndex = 0;
      int multiplChoiceIndex = 0;
      for (ConfigBean configBean in recordConfigBean.list) {
        if (configBean.type == "单选") {

          int  singleIndex = singleIndexs[singleChoiceIndex];
          if (singleIndex != -1 && configBean.optionalAnswers.length > 0) {
            String obj = configBean.optionalAnswers[singleIndex];
            debugPrint("obj:$obj");
            addFollowingRecord(configBean.title, obj, configBean.inputType);
          } else {
            if (configBean.isRequired == 1) {
              showWidgetToast(getToastTipWidget(configBean.title + "项不能为空"));
              canContinue = false;
              break;
            }
            addFollowingRecord(configBean.title, "", configBean.inputType);
          }
          singleChoiceIndex++;

        } else if (configBean.type == "多选") {

          List<int> multipleIndexList = multipleIndexLists[multiplChoiceIndex];

          if (multipleIndexList.length > 0 &&
              configBean.optionalAnswers.length > 0) {

            String answer = configBean.optionalAnswers[multipleIndexList[0]];
            for (int i = 1; i < multipleIndexList.length; i++) {
              String obj = configBean.optionalAnswers[multipleIndexList[i]];
              answer += ("|" + obj);
              debugPrint("obj:$answer");
            }
            addFollowingRecord(configBean.title, answer, configBean.inputType);
          } else {
            if (configBean.isRequired == 1) {
              showWidgetToast(getToastTipWidget(configBean.title + "项不能为空"));
              canContinue = false;
              break;
            }
            addFollowingRecord(configBean.title, "", configBean.inputType);
          }
          multiplChoiceIndex++;
        } else if (configBean.type == "填写") {
          if (configBean.inputType == "单行数字") {
            if (stringEmpty(priceContents[priceIndex])) {
              if (configBean.isRequired == 1) {
                showWidgetToast(getToastTipWidget(configBean.title + "项不能为空"));
                canContinue = false;
                break;
              }
              addFollowingRecord(configBean.title, priceContents[priceIndex],
                  configBean.inputType);
            } else {
              debugPrint("价格:${priceContents[priceIndex]}");
              addFollowingRecord(configBean.title, priceContents[priceIndex],
                  configBean.inputType);
            }
            priceIndex++;
          } else {
            //多行 或者 单行
            if (stringEmpty(remarkContents[index])) {
              if (configBean.isRequired == 1) {
                showWidgetToast(getToastTipWidget(configBean.title + "项不能为空"));
                canContinue = false;
                break;
              }
              addFollowingRecord(configBean.title, remarkContents[index],
                  configBean.inputType);
            } else {
              debugPrint("备注:${remarkContents[index]}");
              addFollowingRecord(configBean.title, remarkContents[index],
                  configBean.inputType);
            }
            index++;
          }
        } else {
          //下拉

          List<int> selectIndexList = selectIndexLists[downIndex];
          if (selectIndexList.length == 0) {
            if (configBean.isRequired == 1) {
              showWidgetToast(getToastTipWidget(configBean.title + "项不能为空"));
              canContinue = false;
              break;
            }
            addFollowingRecord(configBean.title, "", configBean.inputType);
          } else {
            if (configBean.optionalAnswers.length > 0) {
              int next = selectIndexList[0];
              String str = configBean.optionalAnswers[next];
              debugPrint("下拉选择了:$str");
              addFollowingRecord(configBean.title, str, configBean.inputType);
            }
          }
        }
      }
      String res = submitMapList.toString();
      debugPrint("结果: $res");
      if (!canContinue) return;
      loadSubmitFollowingRecords(context);
    }
  }

  List<Widget> getSliverToBoxAdapters() {
    List<Widget> boxAdapters = List<Widget>();
    if (recordConfigBean != null &&
        recordConfigBean.list != null &&
        recordConfigBean.list.length > 0) {
      int remarkIndex = 0;
      int downIndex = 0;
      int priceIndex = 0;
      int singleChoiceIndex = 0;
      int multiplChoiceIndex = 0;

      for (ConfigBean configBean in recordConfigBean.list) {
        if (configBean == null) continue;
        if (configBean.type == "单选") {
          int  singleIndex = singleIndexs[singleChoiceIndex];
          int temp = singleChoiceIndex;
          boxAdapters.add(SliverToBoxAdapter(
            child: WidgetRecordChoice(
              configBean: configBean,
              selectIndex: singleIndex,
              singleChoiceCallback: (value) {
                FocusScope.of(context).requestFocus(FocusNode());
                debugPrint('选中了第$value项');
                singleIndexs[temp] = value;
                setState(() {});

              },
            ),
          ));
          singleChoiceIndex++;
        } else if (configBean.type == "多选") {

          List<int> multipleIndexList = multipleIndexLists[multiplChoiceIndex];
          int tempIndex  =  multiplChoiceIndex;
          boxAdapters.add(SliverToBoxAdapter(
            child: WidgetRecordChoice(
              configBean: configBean,
              multipleChoiceCallback: (List<int> values) {
                FocusScope.of(context).requestFocus(FocusNode());
                for (int value in values) {
                  debugPrint('选中了第$value项');
                }
                multipleIndexLists[tempIndex] = values;
                setState(() {});
              },
              indexList: multipleIndexList,
            ),
          ));
          multiplChoiceIndex++;
        } else if (configBean.type == "填写") {
          if (configBean.inputType == "单行数字") {
            boxAdapters.add(SliverToBoxAdapter(
              child: RecordPriceWidget(
                configBean: configBean,
                priceEditingController: priceControllers[priceIndex],
                content: "dsds",
                singleChoiceCallback: () {},
              ),
            ));
            priceIndex++;
          } else {
            TextEditingController remarkController =
                remarkControllers[remarkIndex];
            FocusNode focusNode = focusNodes[remarkIndex];
            //多行 当行
            boxAdapters.add(SliverToBoxAdapter(
              child: MutipleRemarkWidget(
                title: configBean.title,
                placeholder: configBean.placeholder,
                maxLength: configBean.maxWords,
                controller: remarkController,
                focusNode: focusNode,
                showWaringText: true,
                readOnly: false,
              ),
            ));
            remarkIndex++;
          }
        } else {
          //下拉
          int tempIndex = downIndex;
          List<int> selectIndexList = selectIndexLists[downIndex];
          DkPicker timePicker = timePickers[downIndex];
          int index = selectIndexList.length > 0 ? selectIndexList[0] : -1;
          String sectContent = "";
          if (index != -1) {
            sectContent = configBean.optionalAnswers[index];
          }
          boxAdapters.add(
            SliverToBoxAdapter(
                child: RecordSelectTimeWidget(
              configBean: configBean,
              content: sectContent,
              singleChoiceCallback: () {
                if (null == timePicker) {
                  timePicker = DkPicker(
                    textAlign: TextAlign.center,
                    title: Text(
                      '选择签约年限',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: Color(0xff999999),
                        fontSize: 14,
                      ),
                    ),
                    confirmText: "完成",
                    containerColor: Color(0xffebebeb),
                    cancelTextStyle: TextStyle(
                      color: Color(0xff999999),
                      fontSize: 14,
                    ),
                    adapter: PickerDataAdapter<String>(
                        pickerdata: configBean.optionalAnswers),
                    onConfirm: (DkPicker picker, List value) {
                      selectIndexLists[tempIndex] = value;
                      setState(() {});
                    },
                  );
                  timePickers[tempIndex] = timePicker;
                }
                timePicker.selectedList = selectIndexList;
                timePicker.showModal(context);
              },
            )),
          );
          downIndex++;
        }
      }
    }
    if (historyRecordBean != null) {
      boxAdapters.add(SliverToBoxAdapter(
        child: StepColumnWidget(
          historyRecordBean,
          itemClick: _onItemClick
        ),
      ));
    }
    return boxAdapters;
  }

  _onItemClick(int position) {
    RecordBean recordBean = historyRecordBean.list[position];
    RouteUtil.goPage(CommonWidgetRoute.COMMON_FOLLOWING_RECORD_DETAIL,
        params: {"dataId": recordBean.dataId.toString()});
  }

  void loadHistoryRecords() {
    Map<String, dynamic> paramsMap = {};
    paramsMap["model_name"] = "house_resources";
    paramsMap["model_id"] = widget.option.params["dataId"];
    pageBloc.dataHttpGet(
      path: SaleInApi.followRecordHistoryUrl,
      queryMap: paramsMap,
      handleResult: (dynamic data) {
        historyRecordBean = HistoryRecordBean.fromJson(data);
        setState(() {});
        if(objNotEmpty(recordConfigBean) && listEmpty(recordConfigBean.list)) {
          debugPrint("未配置跟进记录");
          showWidgetToast(getToastTipWidget("未配置跟进记录"));
        }
      },
      showLoading: false,
      showFailMsg: false,
      showSuccessMsg: false,
    );
  }

  void loadSubmitFollowingRecords(BuildContext context) {
    Map<String, dynamic> paramsMap = {};
    paramsMap["model_name"] = "house_resources";
    paramsMap["model_id"] = widget.option.params["dataId"];
    paramsMap["model_value"] = widget.option.params["houseStatus"];
    paramsMap["answers"] = submitMapList;
    pageBloc.dataHttpPost(
        path: SaleInApi.followRecordSubmitUrl,
        data: paramsMap,
        handleResult: (dynamic data) {
          if (data != null) {
            String res = data.toString();
            debugPrint("返回数据:$res");
            String url = data["url"];
            if(url!= null && url.length > 0) {
              RouteUtil.goPage(url);
            }
          }
        },
        showLoading: true,
        showFailMsg: false,
        showSuccessMsg: false,
        handleErrorCode: (value) {
          if (value.code != "0000" && value.msg!= null) {
            showWidgetToast(getToastTipWidget(value.msg));
          }
        });
  }
  @override
  void dispose() {
    super.dispose();
    for (TextEditingController controller in remarkControllers) {
      controller.dispose();
    }

    for (TextEditingController controller in priceControllers) {
      controller.dispose();
    }
  }
}
